<template>
  <view 
    class="floating-reminder" 
    :style="floatingStyle" 
    @touchmove="moveReminder" 
    @touchstart="touchStart"
    :class="{ minimized: isMinimized, 'soon-remind': isComingSoon }"
    v-if="active && nextReminder"
  >
    <!-- 最小化状态 -->
    <view class="reminder-icon" v-if="isMinimized" @tap="handleIconClick">
      <text class="iconfont icon-reminder"></text>
      <view class="countdown-indicator" v-if="remainingSeconds < 3600">
        <text>{{ formatTimeDisplay }}</text>
      </view>
    </view>

    <!-- 展开状态 -->
    <view class="reminder-content" v-else>
      <view class="reminder-header" :class="'type-' + nextReminder.type">
        <text class="reminder-type">{{ getReminderTypeText(nextReminder.type) }}</text>
        <view class="reminder-actions">
          <view class="action-btn minimize-btn" @tap="toggleMinimize">
            <text class="iconfont icon-minimize"></text>
          </view>
          <view class="action-btn close-btn" @tap="closeReminder">
            <text class="iconfont icon-close"></text>
          </view>
        </view>
      </view>
      <view class="reminder-title">{{ nextReminder.title }}</view>
      <view class="reminder-countdown">
        <view class="progress-bar">
          <view class="progress-fill" :style="{ width: progressPercentage + '%' }"></view>
        </view>
        <view class="time-display">
          <view class="time-parts">
            <text v-if="remainingHours > 0" class="time-part">{{ remainingHours }}小时</text>
            <text class="time-part">{{ remainingMinutes }}分钟</text>
            <text class="time-part">{{ remainingSeconds % 60 }}秒</text>
          </view>
          <text class="time-at">{{ nextReminder.time }}</text>
        </view>
      </view>
      <view class="reminder-desc" v-if="nextReminder.desc">{{ nextReminder.desc }}</view>
      <view class="reminder-actions-footer">
        <view class="footer-btn view-btn" @tap="viewReminderDetail">
          <text class="iconfont icon-detail"></text>
          <text>查看详情</text>
        </view>
        <view class="footer-btn snooze-btn" @tap="snoozeReminder">
          <text class="iconfont icon-snooze"></text>
          <text>延后提醒</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { getNextReminder } from '@/common/api/reminder.js'

// 状态定义
const active = ref(true) // 是否显示悬浮窗
const nextReminder = ref(null) // 下一个提醒
const isMinimized = ref(true) // 是否最小化
const remainingSeconds = ref(0) // 剩余秒数
const isComingSoon = ref(false) // 是否即将到点（5分钟内）

// 悬浮窗位置
const position = ref({
  left: uni.getStorageSync('reminder_position_left') || 'auto',
  right: uni.getStorageSync('reminder_position_right') || '20rpx',
  top: uni.getStorageSync('reminder_position_top') || '300rpx',
  bottom: uni.getStorageSync('reminder_position_bottom') || 'auto',
})

// 触摸时的起始位置
const touchStartPos = ref({
  x: 0,
  y: 0
})

// 窗口尺寸信息
const windowInfo = ref({
  width: 0,
  height: 0
})

// 更新定时器
let updateTimer = null
// 检查时间定时器
let checkTimer = null
// 倒计时定时器
let countdownTimer = null

// 计算属性：小时、分钟和秒数
const remainingHours = computed(() => Math.floor(remainingSeconds.value / 3600))
const remainingMinutes = computed(() => Math.floor((remainingSeconds.value % 3600) / 60))

// 计算倒计时显示文本
const formatTimeDisplay = computed(() => {
  if (remainingSeconds.value < 60) {
    return `${remainingSeconds.value}秒`
  } else if (remainingSeconds.value < 3600) {
    return `${remainingMinutes.value}分${remainingSeconds.value % 60}秒`
  } else {
    return `${remainingHours.value}时${remainingMinutes.value}分`
  }
})

// 计算进度百分比
const progressPercentage = computed(() => {
  if (!nextReminder.value) return 0
  
  // 计算总时间段（从上次更新到提醒时间）
  const now = new Date()
  const [hour, minute] = nextReminder.value.time.split(':').map(Number)
  
  const reminderTime = new Date()
  reminderTime.setHours(hour, minute, 0, 0)
  
  // 如果提醒时间已过，则计算明天的时间
  if (reminderTime < now) {
    reminderTime.setDate(reminderTime.getDate() + 1)
  }
  
  const totalSeconds = (reminderTime - now) / 1000
  const originalTotalSeconds = 3600 * 3 // 假设总显示时间为3小时
  
  // 如果剩余时间小于3小时，计算进度百分比
  if (totalSeconds <= originalTotalSeconds) {
    return 100 - (totalSeconds / originalTotalSeconds * 100)
  }
  
  return 0 // 如果剩余时间超过3小时，进度为0
})

// 悬浮窗样式
const floatingStyle = computed(() => {
  return {
    left: position.value.left,
    right: position.value.right,
    top: position.value.top,
    bottom: position.value.bottom,
  }
})

// 加载下一个提醒
const loadNextReminder = async () => {
  try {
    const res = await getNextReminder()
    if (res.code === 0 && res.data) {
      nextReminder.value = res.data
      updateRemainingTime() // 更新剩余时间
    } else {
      nextReminder.value = null
      remainingSeconds.value = 0
    }
  } catch (e) {
    console.error('获取下一个提醒失败', e)
    nextReminder.value = null
    remainingSeconds.value = 0
  }
}

// 更新剩余时间
const updateRemainingTime = () => {
  if (!nextReminder.value) {
    remainingSeconds.value = 0
    return
  }
  
  const now = new Date()
  const [hour, minute] = nextReminder.value.time.split(':').map(Number)
  
  const reminderTime = new Date()
  reminderTime.setHours(hour, minute, 0, 0)
  
  // 如果提醒时间已过，则计算明天的时间
  if (reminderTime < now) {
    reminderTime.setDate(reminderTime.getDate() + 1)
  }
  
  // 计算剩余秒数
  remainingSeconds.value = Math.floor((reminderTime - now) / 1000)
  
  // 判断是否即将到点（5分钟内）
  isComingSoon.value = remainingSeconds.value <= 300 && remainingSeconds.value > 0
}

// 倒计时更新
const updateCountdown = () => {
  if (remainingSeconds.value > 0) {
    remainingSeconds.value -= 1
    
    // 更新是否即将到点
    isComingSoon.value = remainingSeconds.value <= 300 && remainingSeconds.value > 0
    
    // 如果倒计时到0，触发提醒
    if (remainingSeconds.value === 0) {
      showReminder()
    }
  }
}

// 检查提醒时间
const checkReminderTime = () => {
  if (!nextReminder.value) return
  
  const now = new Date()
  const currentHour = now.getHours()
  const currentMinute = now.getMinutes()
  const currentTime = `${currentHour.toString().padStart(2, '0')}:${currentMinute.toString().padStart(2, '0')}`
  
  // 如果当前时间与提醒时间匹配，触发提醒
  if (currentTime === nextReminder.value.time) {
    // 检查今天是否已经触发过这个提醒
    const triggeredReminders = uni.getStorageSync('triggered_reminders') || {}
    const today = now.toISOString().split('T')[0]
    const key = `${today}_${nextReminder.value.id}_${currentTime}`
    
    if (!triggeredReminders[key]) {
      // 标记为已触发
      triggeredReminders[key] = true
      uni.setStorageSync('triggered_reminders', triggeredReminders)
      
      // 更新提醒的触发时间
      const reminders = uni.getStorageSync('reminders') || []
      const index = reminders.findIndex(r => r.id === nextReminder.value.id)
      if (index !== -1) {
        reminders[index].lastTriggered = now.toISOString()
        uni.setStorageSync('reminders', reminders)
      }
      
      // 显示提醒
      showReminder()
      
      // 重新加载下一个提醒
      setTimeout(() => {
        loadNextReminder()
      }, 1000)
    }
  }
}

// 切换最小化状态
const toggleMinimize = () => {
  isMinimized.value = !isMinimized.value
}

// 点击悬浮球图标时的处理
const handleIconClick = () => {
  if (remainingSeconds.value < 300) {
    // 如果剩余时间小于5分钟，直接显示提醒详情
    viewReminderDetail()
  } else {
    // 否则切换展开/收起状态
    toggleMinimize()
  }
}

// 关闭悬浮窗
const closeReminder = () => {
  active.value = false
  // 发送关闭事件
  emit('close')
}

// 查看提醒详情
const viewReminderDetail = () => {
  if (nextReminder.value) {
    uni.navigateTo({
      url: `/pages/reminder/detail?id=${nextReminder.value.id}`
    })
  }
}

// 延后提醒（推迟10分钟）
const snoozeReminder = () => {
  if (!nextReminder.value) return
  
  remainingSeconds.value += 600 // 增加10分钟
  
  uni.showToast({
    title: '已延后10分钟',
    icon: 'success'
  })
}

// 显示提醒通知
const showReminder = () => {
  if (!nextReminder.value) return
  
  // 展开提醒窗口
  isMinimized.value = false
  
  // 显示通知
  uni.showModal({
    title: getReminderTypeText(nextReminder.value.type) + '提醒',
    content: nextReminder.value.title + (nextReminder.value.desc ? '\n' + nextReminder.value.desc : ''),
    confirmText: '我知道了',
    cancelText: '延后10分钟',
    success: (res) => {
      if (res.confirm) {
        console.log('用户确认提醒')
        // 确认后重新加载下一个提醒
        loadNextReminder()
      } else if (res.cancel) {
        console.log('用户延后提醒')
        snoozeReminder()
      }
    }
  })
  
  // 震动提醒
  uni.vibrateShort({
    success: function() {
      console.log('震动成功')
    }
  })
}

// 触摸开始
const touchStart = (e) => {
  const touch = e.touches[0]
  touchStartPos.value = {
    x: touch.clientX,
    y: touch.clientY
  }
}

// 移动悬浮窗
const moveReminder = (e) => {
  // 阻止页面滚动
  e.preventDefault()
  e.stopPropagation()
  
  const touch = e.touches[0]
  const deltaX = touch.clientX - touchStartPos.value.x
  const deltaY = touch.clientY - touchStartPos.value.y
  
  // 转换像素到rpx (窗口宽度/750)
  const pxToRpx = 750 / windowInfo.value.width
  
  // 重新计算位置
  if (position.value.left !== 'auto') {
    let newLeft = parseInt(position.value.left) + deltaX * pxToRpx
    newLeft = Math.max(0, Math.min(newLeft, 630)) // 限制在屏幕内
    position.value.left = newLeft + 'rpx'
  } else if (position.value.right !== 'auto') {
    let newRight = parseInt(position.value.right) - deltaX * pxToRpx
    newRight = Math.max(0, Math.min(newRight, 630)) // 限制在屏幕内
    position.value.right = newRight + 'rpx'
  }
  
  if (position.value.top !== 'auto') {
    let newTop = parseInt(position.value.top) + deltaY * pxToRpx
    newTop = Math.max(0, Math.min(newTop, 1000)) // 限制在屏幕内
    position.value.top = newTop + 'rpx'
  } else if (position.value.bottom !== 'auto') {
    let newBottom = parseInt(position.value.bottom) - deltaY * pxToRpx
    newBottom = Math.max(0, Math.min(newBottom, 1000)) // 限制在屏幕内
    position.value.bottom = newBottom + 'rpx'
  }
  
  // 更新起始位置
  touchStartPos.value = {
    x: touch.clientX,
    y: touch.clientY
  }
  
  // 保存位置到本地存储
  savePosition()
}

// 保存位置到本地存储
const savePosition = () => {
  uni.setStorageSync('reminder_position_left', position.value.left)
  uni.setStorageSync('reminder_position_right', position.value.right)
  uni.setStorageSync('reminder_position_top', position.value.top)
  uni.setStorageSync('reminder_position_bottom', position.value.bottom)
}

// 获取提醒类型文本
const getReminderTypeText = (type) => {
  const typeMap = {
    'medicine': '服药',
    'bloodSugar': '血糖检测',
    'exercise': '运动',
    'diet': '饮食',
    'other': '其他'
  }
  return typeMap[type] || '提醒'
}

// 定义emit
const emit = defineEmits(['close'])

// 监听nextReminder变化
watch(nextReminder, (newValue) => {
  if (newValue) {
    updateRemainingTime()
  }
})

// 生命周期钩子
onMounted(() => {
  // 获取窗口尺寸
  const info = uni.getSystemInfoSync()
  windowInfo.value.width = info.windowWidth
  windowInfo.value.height = info.windowHeight
  
  // 初始加载下一个提醒
  loadNextReminder()
  
  // 设置定时器，每分钟更新一次
  updateTimer = setInterval(() => {
    loadNextReminder()
  }, 60000)
  
  // 设置定时检查提醒时间的定时器，每分钟检查一次
  checkTimer = setInterval(() => {
    checkReminderTime()
  }, 60000)
  
  // 设置倒计时定时器，每秒更新一次
  countdownTimer = setInterval(() => {
    updateCountdown()
  }, 1000)
})

onBeforeUnmount(() => {
  // 清除定时器
  if (updateTimer) {
    clearInterval(updateTimer)
    updateTimer = null
  }
  
  if (checkTimer) {
    clearInterval(checkTimer)
    checkTimer = null
  }
  
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
})
</script>

<style lang="scss">
.floating-reminder {
  position: fixed;
  z-index: 999;
  transition: all 0.3s ease;
  
  &.minimized {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #8cc9a1 0%, #5daa7f 100%);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
    
    &.soon-remind {
      animation: pulse 1.5s infinite alternate;
    }
    
    .reminder-icon {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      
      .iconfont {
        font-size: 44rpx;
        color: #fff;
      }
      
      .countdown-indicator {
        position: absolute;
        bottom: -20rpx;
        left: 50%;
        transform: translateX(-50%);
        background-color: #ff9900;
        color: #fff;
        font-size: 20rpx;
        padding: 4rpx 12rpx;
        border-radius: 20rpx;
        white-space: nowrap;
        box-shadow: 0 2rpx 8rpx rgba(255, 153, 0, 0.3);
      }
    }
  }
  
  .reminder-content {
    width: 440rpx;
    background-color: #fff;
    border-radius: 16rpx;
    box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
    padding: 0;
    overflow: hidden;
    
    .reminder-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx;
      background: linear-gradient(135deg, #8cc9a1 0%, #5daa7f 100%);
      
      &.type-medicine {
        background: linear-gradient(135deg, #5e9dff 0%, #3a7fdb 100%);
      }
      
      &.type-bloodSugar {
        background: linear-gradient(135deg, #ff6b6b 0%, #e04848 100%);
      }
      
      &.type-exercise {
        background: linear-gradient(135deg, #ffaa5e 0%, #ff8c2c 100%);
      }
      
      &.type-diet {
        background: linear-gradient(135deg, #8cc9a1 0%, #5daa7f 100%);
      }
      
      &.type-other {
        background: linear-gradient(135deg, #a18cff 0%, #8269e6 100%);
      }
      
      .reminder-type {
        font-size: 26rpx;
        color: #fff;
        font-weight: bold;
      }
      
      .reminder-actions {
        display: flex;
        
        .action-btn {
          width: 44rpx;
          height: 44rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 50%;
          background-color: rgba(255, 255, 255, 0.2);
          margin-left: 16rpx;
          
          .iconfont {
            font-size: 24rpx;
            color: #fff;
          }
          
          &:active {
            background-color: rgba(255, 255, 255, 0.4);
          }
        }
      }
    }
    
    .reminder-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin: 24rpx;
    }
    
    .reminder-countdown {
      margin: 0 24rpx 24rpx;
      
      .progress-bar {
        height: 8rpx;
        background-color: #f0f0f0;
        border-radius: 4rpx;
        overflow: hidden;
        margin-bottom: 16rpx;
        
        .progress-fill {
          height: 100%;
          background: linear-gradient(to right, #8cc9a1, #ff9900);
          border-radius: 4rpx;
          transition: width 1s linear;
        }
      }
      
      .time-display {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .time-parts {
          display: flex;
          
          .time-part {
            font-size: 28rpx;
            color: #ff9900;
            font-weight: 500;
            margin-right: 8rpx;
          }
        }
        
        .time-at {
          font-size: 26rpx;
          color: #666;
          font-weight: bold;
        }
      }
    }
    
    .reminder-desc {
      margin: 0 24rpx 24rpx;
      font-size: 26rpx;
      color: #666;
      line-height: 1.6;
      padding: 16rpx;
      background-color: #f9f9f9;
      border-radius: 12rpx;
    }
    
    .reminder-actions-footer {
      display: flex;
      border-top: 1px solid #f0f0f0;
      
      .footer-btn {
        flex: 1;
        height: 80rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26rpx;
        
        &:first-child {
          border-right: 1px solid #f0f0f0;
        }
        
        &.view-btn {
          color: #8cc9a1;
        }
        
        &.snooze-btn {
          color: #ff9900;
        }
        
        .iconfont {
          margin-right: 8rpx;
          font-size: 28rpx;
        }
        
        &:active {
          background-color: #f9f9f9;
        }
      }
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
  }
  100% {
    transform: scale(1.1);
    box-shadow: 0 8rpx 24rpx rgba(255, 153, 0, 0.3);
  }
}
</style> 